<!-- 代办任务 -->
<template>
  <div>
    <a-spin :loading="agentspinning" style="height: 100%">
      <a-row type="flex">
        <a-col :span="10">
          <div class="cardList">
            <div style="display: flex; align-items: center; margin-bottom: 8px">
              <a-input
                :allow-clear="true"
                class="custom-input"
                v-model="queryParam.name"
                placeholder="输入搜索"
              >
                <template #suffix>
                  <a-tooltip>
                    <template #content>搜索</template>
                    <span
                      v-if="!queryParam.name"
                      style="color: var(--color-text-3)"
                      >🔍</span
                    >
                  </a-tooltip>
                </template>
              </a-input>
              <a-dropdown>
                <div
                  class="ant-dropdown-link"
                  style="
                    justify-content: center;
                    font-weight: 400;
                    text-align: right;
                    font-size: 14px;
                    color: var(--color-text-2);
                    display: flex;
                    align-items: center;
                    width: 130px;
                    margin-left: 16px;
                    padding: 5.5px 8px;
                  "
                  @click="(e) => e.preventDefault()"
                >
                  {{ queryParamType }} <span style="margin-left: 4px">⌄</span>
                </div>
                <template #content>
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = 'all'),
                          (queryParamType = '全部状态'));
                      }
                    "
                    >全部状态</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = 'running'),
                          (queryParamType = '处理中'));
                      }
                    "
                    >处理中</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = 'finish'),
                          (queryParamType = '完成'));
                      }
                    "
                    >完成</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = '驳回'),
                          (queryParamType = '驳回'));
                      }
                    "
                    >驳回</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = 'fail'),
                          (queryParamType = '失败'));
                      }
                    "
                    >失败</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = 'end'),
                          (queryParamType = '撤销'));
                      }
                    "
                    >撤销</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = '结束'),
                          (queryParamType = '结束'));
                      }
                    "
                    >结束</a-doption
                  >
                  <a-doption
                    @click="
                      () => {
                        ((queryParam.Status = 'reissue'),
                          (queryParamType = '重新发起'));
                      }
                    "
                    >重新发起</a-doption
                  >
                </template>
              </a-dropdown>
            </div>
            <div class="scroll-container" v-if="data.length !== 0">
              <div
                :class="{
                  active: item?.instanceId === selectagent?.instanceId,
                }"
                v-for="(item, index) in data"
                :key="index"
                class="card"
                :style="[
                  { margin: index == 0 ? '0px 0px 8px 0px' : '8px 0px' },
                  item?.instanceId === selectagent?.instanceId
                    ? {
                        border: '2px solid #2983FF',
                        boxSizing: 'border-box',
                        boxShadow: 'inset 0 0 0 1px #2983FF',
                        background: '#fff',
                      }
                    : {
                        border: '1.5px solid transparent',
                        boxSizing: 'border-box',
                      },
                ]"
                @click="
                  item?.instanceId !== selectagent?.instanceId
                    ? examineClick(item)
                    : false
                "
              >
                <div>
                  <ul style="display: flex">
                    <li v-if="participate">
                      <span>
                        <img
                          style="width: 20px; height: 20px; margin-right: 5px"
                          src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png"
                        />
                      </span>
                      <div
                        style="
                          font-size: 16px;
                          font-weight: bold;
                          color: var(--color-text-1);
                        "
                        :ellipsis="{ tooltip: true }"
                      >
                        <OverflowText
                          style="font-weight: 500"
                          :text="
                            cropname(item.serviceItemTitle, item.createName)
                          "
                          :maxWidth="'180px'"
                        />
                      </div>
                    </li>
                    <li v-else>
                      <div
                        style="
                          font-size: 16px;
                          font-weight: bold;
                          color: var(--color-text-1);
                        "
                        :ellipsis="{ tooltip: true }"
                      >
                        <OverflowText
                          style="font-weight: 500"
                          :text="item.serviceItemTitle"
                          :maxWidth="'180px'"
                        />
                      </div>
                    </li>
                    <li>
                      <div
                        v-if="['end', 'fail'].includes(item.processStatus)"
                        style="
                          text-align: center;
                          color: var(--color-text-inverse);
                          background: var(--color-danger-6);
                          border-radius: 2px;
                          margin-right: 0px;
                          width: 65px;
                          font-size: 12px;
                          line-height: 20px;
                          height: 22px;
                        "
                      >
                        {{ getTagColor(item.processStatus).title }}
                      </div>
                      <div v-else>
                        <a-tag
                          :color="getTagColor(item.processStatus).color"
                          style="
                            text-align: center;
                            border-radius: 999px;
                            margin-right: 0px;
                            width: 65px;
                          "
                        >
                          {{ getTagColor(item.processStatus).title }}
                        </a-tag>
                      </div>
                    </li>
                  </ul>
                </div>
                <div v-if="item.tag">
                  <span
                    style="display: flex; margin: 0px; padding: 3px"
                    v-for="(value, key, tagindex) in JSON.parse(item.tag)"
                    :key="tagindex"
                  >
                    <!-- <div style="font-size: 13px;color: #646A73;font-size: 14px;">{{ key }}</div>
                    <div style="color: #222B3C;padding-left: 5px;font-size: 14px;">:{{ value }}</div> -->
                    <OverflowText
                      style="
                        font-size: 13px;
                        color: var(--color-text-2);
                        font-size: 14px;
                      "
                      :text="String(key)"
                      :maxWidth="'85px'"
                    />:
                    <OverflowText
                      style="
                        color: var(--color-text-1);
                        padding-left: 5px;
                        font-size: 14px;
                        flex: 1;
                      "
                      :text="String(value)"
                    />
                  </span>
                </div>
                <div>
                  <!-- 先空着接口没给 -->
                  <ul style="display: flex; height: 23px">
                    <li>
                      <a-tag
                        v-if="item.nodeName"
                        style="
                          font-size: 12px;
                          background-color: var(--color-fill-4);
                          border-color: var(--color-border-3);
                          border-radius: 4px;
                          height: 22px;
                          line-height: 22px;
                          padding: 0 8px;
                          display: inline-flex;
                          align-items: center;
                        "
                      >
                        <!-- <a-tooltip :title="item.nodeName">
                          <div :ellipsis="{ tooltip: true }" class="titleUtils" :style="{color:item.processStatus ==='running' || item.processStatus ==='fail'?'#2983FF':'#515665'}" style="max-width:108px;font-size: 12px;font-weight: 400;">
                            {{ item.processStatus ==='running' && item.nodeName.length>1?`共${item.nodeName.length}个进行中`:item.nodeName[0] }}
                          </div>
                        </a-tooltip> -->
                        <OverflowText
                          :style="{
                            color:
                              item.processStatus === 'running'
                                ? 'var(--color-primary-6)'
                                : 'var(--color-text-2)',
                          }"
                          style="font-size: 12px; font-weight: 400"
                          :text="
                            item.processStatus === 'running' &&
                            item.nodeName.length > 1
                              ? `共${item.nodeName.length}个进行中`
                              : item.nodeName[0]
                          "
                          :maxWidth="'108px'"
                        />
                      </a-tag>
                    </li>
                    <li>
                      <div
                        class="limited-container"
                        style="
                          color: var(--color-text-3);
                          font-size: 12px;
                          line-height: 20px;
                        "
                      >
                        <p v-if="item.nodeName">
                          <span>
                            {{
                              JSON.stringify(item.nodeName).length < 9
                                ? "发起时间"
                                : ""
                            }}
                            {{ transferDate(item.createTime) }}</span
                          >
                        </p>
                        <p v-else>
                          <span
                            >发起时间: {{ transferDate(item.createTime) }}</span
                          >
                        </p>
                      </div>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
            <div
              v-else
              style="
                color: var(--color-text-3);
                text-align: center;
                margin-top: 100px;
              "
            >
              暂无数据
            </div>
          </div>
        </a-col>
        <a-col :span="14" style="border-radius: 0px 0px 8px 0px">
          <div class="agentcontent" style="height: 100%">
            <div v-if="selectagent" class="agent">
              <div>
                <ul class="agent-header">
                  <li
                    style="
                      margin-right: 12px;
                      font-size: 18px;
                      font-weight: 500;
                      color: var(--color-text-1);
                    "
                  >
                    {{ selectagent.serviceItemTitle }}
                  </li>
                  <!-- 移除竖向分隔线，避免右侧出现多余的长条视觉元素 -->
                  <li
                    style="
                      margin-right: 12px;
                      display: flex;
                      align-items: center;
                    "
                  >
                    <div
                      style="
                        font-size: 14px;
                        color: var(--color-text-3);
                        font-weight: 400;
                      "
                    >
                      <OverflowText
                        style="
                          font-size: 14px;
                          line-height: 14px;
                          color: var(--color-text-1);
                          padding-left: 5px;
                        "
                        :text="selectagent.createName"
                        :maxWidth="'100px'"
                      />
                    </div>
                  </li>
                  <li style="margin-right: 24px">
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        font-size: 14px;
                        color: var(--color-text-3);
                        font-weight: 400;
                        line-height: 16px;
                      "
                    >
                      <div>发起于</div>
                      <div style="padding-left: 5px">
                        {{ transferDate(selectagent.createTime) }}
                      </div>
                    </div>
                  </li>
                  <li style="line-height: 16px; margin-right: 4px">
                    <div style="display: flex; align-items: center">
                      <div
                        style="
                          font-size: 14px;
                          color: var(--color-text-3);
                          line-height: 16px;
                          font-weight: 400;
                        "
                      >
                        工单状态:
                      </div>
                      <div
                        style="color: var(--color-text-1); padding-left: 5px"
                      >
                        <div
                          v-if="
                            ['end', 'fail'].includes(selectagent.processStatus)
                          "
                          style="
                            text-align: center;
                            color: var(--color-text-inverse);
                            background: var(--color-danger-6);
                            border-radius: 999px;
                            margin-right: 0px;
                            width: 65px;
                            font-size: 12px;
                            line-height: 22px;
                            height: 22px;
                          "
                        >
                          {{ getTagColor(selectagent.processStatus).title }}
                        </div>
                        <div v-else>
                          <a-tag
                            :color="
                              getTagColor(selectagent.processStatus).color
                            "
                            style="
                              text-align: center;
                              border-radius: 999px;
                              margin-right: 0px;
                              width: 65px;
                            "
                          >
                            {{ getTagColor(selectagent.processStatus).title }}
                          </a-tag>
                        </div>
                      </div>
                    </div>
                  </li>
                  <!-- ['end','fail'].includes(selectagent.processStatus) -->
                  <li
                    v-if="
                      ['end', 'fail'].includes(selectagent.processStatus) &&
                      selectagent.errorMsg
                    "
                    style="line-height: 16px"
                  >
                    <div style="display: flex; align-items: center">
                      <div
                        style="color: var(--color-text-1); padding-left: 5px"
                      >
                        <a-popover placement="leftTop">
                          <template #content>
                            <div
                              class="scroll-container"
                              style="
                                width: 500px;
                                height: 400px;
                                color: var(--color-text-2);
                                border-color: var(--color-danger-3);
                              "
                            >
                              {{ selectagent.errorMsg }}
                            </div>
                          </template>
                          <a-tag
                            color="#FEF0F0"
                            class="titleUtils"
                            style="
                              max-width: 166px;
                              color: var(--color-text-2);
                              font-size: 12px;
                              text-align: center;
                              border-radius: 999px;
                              margin-right: 0px;
                            "
                          >
                            {{ selectagent.errorMsg }}
                          </a-tag>
                        </a-popover>
                      </div>
                    </div>
                  </li>
                </ul>
              </div>
              <div>
                <div>
                  <a-tabs
                    v-model:active-key="activeKey"
                    default-active-key="1"
                    force-render
                    @change="callbackTab"
                  >
                    <a-tab-pane key="1">
                      <template #title>
                        <span
                          :style="{
                            color:
                              callbackTab === 1
                                ? 'var(--color-text-1)'
                                : 'var(--color-primary-6)',
                          }"
                          style="font-size: 14px"
                          class="bold-tab"
                          >节点详情</span
                        >
                      </template>
                      <div v-if="participate">
                        <home-timeline
                          style="margin-top: 10px"
                          v-if="showModule && myActivityList.length > 0"
                          :style="{ height: participate ? '543px' : '575px' }"
                          :fromList="myActivityList"
                          :participate="participate"
                        ></home-timeline>
                      </div>
                      <div v-else>
                        <div
                          class="scroll-container"
                          style="
                            height: 525px;
                            padding: 10px 20px;
                            margin-top: 12px;
                          "
                        >
                          <!-- 驳回的话能重新发起 -->
                          <form-model
                            v-if="
                              !participate &&
                              selectagent.processStatus === '驳回' &&
                              appVisible
                            "
                            :ref="approVal.ref"
                            :modalObj="modalObj"
                            :dataObj="approVal.dataObj"
                          >
                          </form-model>
                          <DetailsModel
                            v-else-if="appVisible"
                            :ref="approVal.ref"
                            :modalObj="modalObj"
                            :dataObj="approVal.dataObj"
                          >
                          </DetailsModel>
                        </div>
                        <a-divider
                          v-if="selectagent.processStatus === '驳回'"
                        />
                        <!-- <div style="height: 50px;display: flex;align-items: center;" v-if="selectagent.processStatus === '驳回'"> -->
                        <div
                          style="
                            height: 50px;
                            display: flex;
                            align-items: center;
                          "
                        >
                          <a-button
                            v-if="
                              !participate &&
                              selectagent.processStatus === '驳回'
                            "
                            type="primary"
                            style="margin-right: 8px"
                            @click="ReRun(selectagent)"
                            ghost
                          >
                            重新发起
                          </a-button>
                          <!-- running -->
                          <a-button
                            class="cancel"
                            v-if="
                              !participate &&
                              selectagent.processStatus === 'running'
                            "
                            type="text"
                            style="color: var(--color-text-2)"
                            @click="termination(selectagent)"
                          >
                            <svg
                              class="icon"
                              style="
                                font-size: 14px;
                                margin-right: 8px;
                                color: var(--color-text-2);
                              "
                              aria-hidden="true"
                            >
                              <use :xlink:href="`#icon-guanji`"></use>
                            </svg>
                            撤销
                          </a-button>
                        </div>
                        <!-- <div style="height: 50px;display: flex;align-items: center;" v-else></div> -->
                      </div>
                    </a-tab-pane>
                    <a-tab-pane key="2">
                      <template #title>
                        <span
                          :style="{
                            color:
                              callbackTab === 2
                                ? 'var(--color-text-1)'
                                : 'var(--color-primary-6)',
                          }"
                          style="font-size: 14px"
                          class="bold-tab"
                          >流转记录</span
                        >
                      </template>
                      <a-checkbox
                        v-if="participate"
                        @click="isMeObj"
                        v-model="isMe"
                        style="
                          color: var(--color-text-2);
                          margin: 12px 0px 10px 0px;
                          font-size: 14px;
                        "
                      >
                        只看我参与的
                      </a-checkbox>
                      <home-timeline
                        v-if="showModule"
                        :style="{ height: participate ? '543px' : '575px' }"
                        :fromList="!isMe ? fromList : myActivityList"
                        :participate="participate"
                      ></home-timeline>
                    </a-tab-pane>
                    <a-tab-pane v-if="false" key="3">
                      <template #title>
                        <span
                          :style="{
                            color:
                              callbackTab === 3
                                ? 'var(--color-text-1)'
                                : 'var(--color-primary-6)',
                          }"
                          style="font-size: 14px"
                          class="bold-tab"
                          >流程图</span
                        >
                      </template>
                      <div style="height: 577px">
                        <a-spin :loading="wokflowSpinning">
                          <processSvg
                            style="margin: 10px 0px"
                            v-if="!wokflowSpinning"
                            ref="fow"
                            :nodekeyMap="nodekeyMap"
                            :styleData="styleData"
                          />
                        </a-spin>
                      </div>
                    </a-tab-pane>
                  </a-tabs>
                </div>
              </div>
            </div>
            <div
              v-else
              class="notData"
              style="padding: 10px; height: 680px; align-items: center"
            >
              <!-- <img src="@/assets/kong.png" /> -->
            </div>
          </div>
          <!-- </a-spin> -->
        </a-col>
      </a-row>
    </a-spin>
  </div>
</template>

<script>
// import processSvg from "@/views/workflow/WorkflowCanvas/workflow/processSvg.vue";
import moment from "moment";
import { nanoid } from "nanoid";
import {
  processCheck as apiProcessCheck,
  processrun as apiProcessrun,
  upWordStatus,
  complete as apiComplete,
  queryProcessView,
  queryCompleted,
  getNodeExecStatus,
} from "@/api/workflow2";
import FormRenderer from "@/components/Form/FormRenderer.vue";
import OverflowText from "@/views/dashboard/workplace/OverflowText.vue";
import { repairUiData } from "@/utils/util.js"; // 修复ui
import { _, cloneDeep } from "lodash";
import {
  queryWorkPage,
  queryJoinWorkPage,
  terminationModel,
  saveUnlimitedValue,
} from "@/api/workplace";

export default {
  components: {
    FormRenderer,
    // DetailsModel,
    OverflowText,
  },
  name: "AgencyTasks",
  data() {
    return {
      queryParamType: "全部状态",
      UrlParamsInstanceId: undefined,
      UrlParamsType: undefined,
      personalSearch: "",
      isMe: false,
      showModule: true,
      viewres: undefined,
      data: [],
      fromList: [],
      myActivityList: [],
      agentspinning: false,
      wokflowSpinning: false,
      selectagent: null,
      appVisible: false,
      logvisible: false,
      styleData: {},
      nodekeyMap: {},
      logData: {},
      showExtraDivs: [],
      approvalStatus: {
        同意: "var(--color-primary-6)",
        拒绝: "var(--color-danger-6)",
        驳回: "var(--color-danger-6)",
      },
      ordertype: [
        // {
        //   key: 'executor',
        //   value: '接单已处理',
        //   color: '#007AFF'
        // },
        {
          key: "notExecutor",
          value: "接单未处理",
          color: "red",
        },
        {
          key: "executorMap",
          value: "团队接单处理人",
          color: "var(--color-fill-3)",
        },
        {
          key: "untreated",
          value: "团队接单未处理人",
          color: "red",
        },
        {
          key: "notAccepted",
          value: "未接单团队",
          color: "var(--color-fill-3)",
        },
      ],
      approVal: {
        ref: "approVal",
        form: {},
        modalObj: { mode: "nodeExe" },
        dataObj: {},
        // 'curPlugBtn': {},
        key: nanoid(),
      },
      activeKey: "1",
      modalObj: { mode: "nodeExe" }, // 模式一定要传
      DetailsdataObj: {},
      queryParam: {
        Status: "all",
      },
    };
  },
  props: {
    participate: {
      type: Boolean,
      default: false,
    },
  },
  created() {},
  async mounted() {
    const urlParams = new URLSearchParams(window.location.search);
    this.UrlParamsInstanceId = urlParams.get("instanceId");
    this.UrlParamsType = urlParams.get("type");
    this.initiatedlinitList();
    // if (this.participate) { // 与我有关时特殊处理
    //   this.callbackTab(2)
    // }
  },
  methods: {
    teamorpersonal() {
      console.log("d112341234");
      this.UrlParamsInstanceId = undefined;
      this.UrlParamsType = undefined;
      this.initiatedlinitList();
    },
    isObjectEmpty(item) {
      return !_.isEmpty(item); // 使用 Lodash 的 isEmpty 方法
    },
    approvalsIndex(item) {
      // 算几个已处理，狗听了摇头
      let index = 0;
      for (const i of JSON.parse(
        JSON.parse(item[item.length - 1].log)[0]?.result
      )) {
        if (i.approvalResult) {
          index++;
        }
      }
      return index;
    },
    // scrollToBottom () {
    //   const container = this.$refs.scrollContainer
    //   container.scrollTop = container.scrollHeight
    // },
    async termination(item) {
      // 撤销 确定撤销？ FC8334
      const self = this;
      this.$confirm({
        title: "确定撤销？",
        icon: (h) =>
          h(
            "svg",
            {
              class: "icon anticon",
              attrs: { "aria-hidden": "true" },
              style: { color: "var(--color-danger-6)", fontSize: "24px" },
            },
            [h("use", { attrs: { "xlink:href": "#icon-tishi1" } })]
          ),
        content: (h) =>
          h("div", [
            h(
              "div",
              { style: { color: "var(--color-danger-6)" } },
              "流程撤销后无法恢复！"
            ),
            h("div", "剩余节点将被关闭，流转产生的数据会回到初始状态"),
          ]),
        async onOk() {
          const { instanceId, processId, processVersion } = item;
          await terminationModel({
            instanceId: instanceId,
            modelId: processId,
            version: processVersion,
          });
          // this.$forceUpdate()
          self.$emit("teamorpersonal");
        },
        onCancel() {},
        class: "alarm",
      });
    },
    async ReRun(item) {
      // 获取formUi提交数据
      const { form, actualValue } =
        await this.$refs[this.approVal.ref].formModelOk();
      const { viewDataMappingDTOList, viewId } = this.viewres.data;

      const serverInfoMap = {
        sponsor: item.createUser,
        tenantId: "1000",
        serviceItemTitle: item.serviceItemTitle,
        serviceItemNumber: item.serviceWorkOrderNumber,
        serviceItemId: item.serviceItemId,
      };
      const data = {
        instanceId: "",
        modelId: item.processId,
        processType: "DEFAULT",
        runVariableMap: form,
        // 'serverInfoMap': {},
        userId: "",
        version: item.processVersion,
        serverInfoMap: serverInfoMap,
      };

      const res = await apiProcessCheck({
        ...data,
        viewId: viewId,
      });
      
      if (res.code !== 200) {
        throw new Error("验证失败");
      }

      const resultCode = await apiProcessrun(data);

      const { instanceId, modelId } = resultCode.data;
      this.viewId = viewId;
      // eslint-disable-next-line no-unused-expressions
      const readUnlimitedMap = viewDataMappingDTOList
        ?.map((item) => {
          if (item.readUnlimited && actualValue[item.dataColumnKey]) {
            return {
              columnKey: item.dataColumnKey,
              instanceId: instanceId,
              taskId: modelId,
              value: actualValue[item.dataColumnKey],
              viewId: viewId,
            };
          }
        })
        .filter(Boolean);
      if (readUnlimitedMap) {
        await saveUnlimitedValue(readUnlimitedMap);
      }

      await upWordStatus(item.id);
      this.$forceUpdate();
      // this.initList()
      this.initiatedlinitList();
    },
    isJsonString(str) {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    },
    logdetails(value, event) {
      // 日志详情
      event.stopPropagation(); // 阻止事件冒泡
      this.logvisible = true;
      this.logData = value;
    },
    loghandleOk() {},
    loghandleCancel() {
      this.logvisible = false;
    },
    checkAllOverflow() {
      const contentDivs = this.$refs.ordertype;
      if (contentDivs) {
        contentDivs.forEach((div, index) => {
          // 判断每个 div 内容是否溢出
          if (div.scrollHeight > div.clientHeight) {
            this.showExtraDivs[index] = true;
          } else {
            this.showExtraDivs[index] = false;
          }
        });
      }
    },
    cropname(serviceItemTitle, createName) {
      // const strval = `${serviceItemTitle}“${createName}”`
      const strval = `${createName}发起的“${serviceItemTitle}”`;
      return strval;
    },
    transferDate(Time) {
      return Time ? moment(parseInt(Time)).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    async callbackTab(val) {
      // 切换审批跟流程视图
      if (val === "1") {
        // 审批
        // eslint-disable-next-line no-unused-expressions
        // this.$refs[this.approVal.ref]?.setEditorKey()// 解决切换tab,富文本返显问题
      } else if (val === "2") {
        // 流转记录
        this.isMe = false;
        this.showModule = false;
        this.$nextTick(() => {
          setTimeout(() => {
            this.showModule = true;
          }, 100);
        });
        await this.$nextTick();
        await this.checkAllOverflow();
      } else if (val === "3") {
        // 流程图
        this.flowchart(this.selectagent);
      }
    },
    async initiatedlinitList() {
      // 发起的
      // const { pageNo, pageSize } = parameter
      const params = {
        serviceItemTitle: this.queryParam.name,
        processStatus:
          this.queryParam.Status === "all" ? "" : this.queryParam.Status,
        instanceId:
          this.UrlParamsInstanceId && this.UrlParamsType === "initiate"
            ? this.UrlParamsInstanceId
            : "",
        pageNo: 1,
        pageSize: 9999,
      };
      const result = this.participate
        ? await queryJoinWorkPage(params)
        : await queryWorkPage(params);
      this.data = result.data.rows.map((item) => ({
        ...item,
        tag: item.tagValue,
      }));
      if (this.data.length > 0) {
        this.selectagent = this.data[0];
        await this.examineClick(this.selectagent);
      }
    },
    async handleOk(buttonitem) {
      try {
        await this.$nextTick();
        await this.$refs[this.approVal.ref].$refs.infoViews.validate(
          async (valid) => {
            // 校验
            if (valid) {
              const { form } =
                await this.$refs[this.approVal.ref].formModelOk();
              const result = await apiComplete({
                param: { ...form, approvalResult: buttonitem.value },
                executionId: this.examineObj.runExecutionId,
                runTaskId: this.examineObj.runTaskId,
                instanceId: this.examineObj.instanceId,
                viewId: this.examineObj.formId,
              });
              if (result.code === 200) {
                // this.initList()
                this.initiatedlinitList();
              }
              this.showComponent = false;
              this.visible = false;
            }
          }
        );
      } catch (e) {
        console.error('请求失败,但走这就对了', e)
      }
    },
    async examineClick(val) {
      console.log("点了？？？");
      this.agentspinning = true;
      try {
        this.appVisible = false;
        this.approVal.dataObj = {};
        this.personalSearch = "";
        this.activeKey = "1";
        this.selectagent = val;
        this.winTitle = val.nodeName;
        const res = await queryProcessView(val.instanceId);
        this.viewres = res;
        this.approVal.dataObj = repairUiData(
          res.data.viewUi,
          res.data.viewDataMappingDTOList
        );
        this.appVisible = true;
        let form;
        if (this.participate) {
          form = {
            ...res.data.viewParam,
            ...res.data.unlimitedParam,
          };
        } else {
          form = res.data.viewParam;
        }

        if (val.processStatus === "驳回") {
          this.$nextTick(async () => {
            await this.$refs.approVal.uploadInitlist(form);
            await this.$refs.approVal.getDataLinkage(
              true,
              this.approVal.dataObj.pageData,
              false
            );
          });
          this.approVal.form = form;
        } else {
          this.$nextTick(async () => {
            // eslint-disable-next-line no-unused-expressions
            this.$refs.approVal?.open("workOrder", form);
          });
        }
        this.serviceUpdate(val);
      } catch (error) {
        console.log("error:", error);
      }
      this.agentspinning = false;
    },
    formUiMap(fromList) {
      // 执行map
      for (const key in fromList) {
        fromList[key] = fromList[key][fromList[key].length - 1];
        fromList[key].formUi = repairUiData(
          fromList[key].formUi,
          fromList[key].viewDataMappingDTOList
        );
        if (fromList[key].appType === "process" && fromList[key].subProcess) {
          // eslint-disable-next-line no-undef
          fromList[key].subProcess = this.formUiMap(
            fromList[key].subProcess.processCompletedNodeResDTOMap
          );
        }
      }
      return Object.values(fromList);
    },
    myActivityMap(fromList, myActivity, _fromList = []) {
      // 执行map
      for (const index in fromList) {
        if (
          fromList[index].appType === "process" &&
          fromList[index].subProcess
        ) {
          // eslint-disable-next-line no-undef
          this.myActivityMap(fromList[index].subProcess, myActivity, _fromList);
        }
        if (myActivity.includes(fromList[index].nodeKey)) {
          _fromList.push(fromList[index]);
        }
      }
      return _fromList;
    },
    isMeObj() {
      this.showModule = false;
      this.$nextTick(() => {
        setTimeout(() => {
          this.showModule = true;
        }, 100);
      });
    },
    async serviceUpdate(data) {
      // 点击查看
      console.log("进来了");
      this.fromList = [];
      this.FormModelShow = true;
      this.visible = true;
      const res = await queryCompleted({
        record: true,
        instanceId: data.instanceId,
        modelId: data.processId,
        version: data.processVersion,
        nodeId: data.nodeId,
      });
      this.form = data;
      this.fromList = this.formUiMap(res.data.processCompletedNodeResDTOMap);
      this.myActivityList = this.myActivityMap(
        cloneDeep(this.fromList),
        res.data.myActivity
      );
    },
    async flowchart(data) {
      // 流程图
      this.wokflowSpinning = true;
      const response = await getNodeExecStatus(
        data.instanceId
      );
      this.wokflowSpinning = false;
      const nodes = response.data.nodes;
      this.nodekeyMap = nodes.reduce((acc, { nodeKey, nodeName }) => {
        acc[nodeKey] = nodeName;
        return acc;
      }, {});
      const nodeStatusMap = nodes.reduce((acc, { nodeKey, nodeStatus }) => {
        acc[nodeKey] = nodeStatus;
        return acc;
      }, {});
      const uiInfo = response.data.model.uiInfo;
      this.styleData = {
        // width: '500px',
        height: "585px",
        scale: 0.5,
      };
      this.$nextTick(() => {
        this.$refs.fow.fowupdata(JSON.parse(uiInfo), nodeStatusMap);
      });
    },
    getTagColor(status) {
      switch (status) {
        case "running":
          return { title: "处理中", color: "blue" }; // 绿色
        case "finish":
          return { title: "完成", color: "" };
        case "fail":
          return { title: "失败", color: "red" }; // 红色
        case "end":
          return { title: "撤销", color: "red" }; // 红色
        case "驳回":
          return { title: "驳回", color: "var(--color-danger-6)" };
        // case 'reject':
        //   return { title: '驳回', color: '#FF8C00' }
        // case 'over':
        //   return { title: '结束', color: 'pink' }
        case "结束":
          return { title: "结束", color: "" };
        case "reissue":
          return { title: "重新发起", color: "" };
        default:
          return "default"; // 默认颜色
      }
    },
  },
  watch: {
    queryParam: {
      // 节流防抖抖抖～～
      handler() {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.initiatedlinitList();
        }, 1000);
      },
      deep: true,
    },
  },
};
</script>

<style lang="less" scoped>
.titleShow {
  width: 182px;
}
:deep(.custom-input .ant-input) {
  border-radius: 9999px;
  background: var(--color-fill-2);
}

:deep(.custom-input .ant-input:focus) {
  background-color: var(--color-bg-2);
}

:deep(.ant-divider-horizontal) {
  margin: 0px;
}
:deep(.ant-timeline-item) {
  padding: 0 0 10px;
}
:deep(.ant-timeline-item-content) {
  top: -10px;
}
:deep(.ant-tabs-tab) {
  font-size: 18px;
}
:deep(.ant-tabs-bar) {
  margin: 0px;
}
:deep(.ant-tag) {
  border-radius: 4px;
}
:deep(.ant-divider) {
  margin: 0px;
  padding: 0px;
}

:deep(.ant-tabs-nav .ant-tabs-tab) {
  padding: 12px 0px;
  color: var(--color-text-1);
  font-size: 18px;
  font-weight: 500;
}

/* 修改选中标签的颜色 */
:deep(.ant-tabs-nav .ant-tabs-tab.ant-tabs-tab-active) {
  color: var(--color-primary-6);
  padding: 12px 0px;
}

/* 修改弹窗内容区域的圆角 */
:deep(.ant-modal-content) {
  border-radius: 8px !important;
}

:deep(.ant-modal-header) {
  border-radius: 8px 8px 0 0 !important;
}

:deep(.ant-spin-container) {
  height: 100% !important;
}

.ant-dropdown-link:hover {
  border-radius: 6px;
  background: var(--color-fill-3);
  cursor: pointer;
}

// .cancel:hover{
//   background: #F7F8FA;
// }
</style>
